﻿namespace ChinaUnicom.ViewModels
{
    using Avatar;
    using Avatar.Commands;
    using Avatar.Schedule;
    using ChinaUnicom.Controls;
    using ChinaUnicom.Models;
    using ChinaUnicom.Tasks;
    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;

    public class FeeHistoriesListContext : PageContext, INotifyPropertyChanged
    {
        ITaskScheduler scheduler;

        public FeeHistoriesListContext()
        {
            ProgressEnabled = false;
            scheduler = SchedulerFactory.Create(SchedulerType.Serial);
            scheduler.Error += OnSchedulerError;
            scheduler.StateChanged += OnSchedulerStateChanged;

            FeeHistories = new FeeHistoryCollection();
            FeeHistories.Add(Context.Current.FeeHistories.OrderByDescending(x => x.Occurred));

            scheduler.Schedule(GenerateFeeHistoriesTask());
        }

        ITask GenerateFeeHistoriesTask()
        {
            FeeHistoriesTask task = new FeeHistoriesTask();
            task.Started += OnTaskStated;
            task.Failed += OnFailed;
            task.Completed += OnTaskCompleted;
            task.Flashed += OnFlashed;

            return task;
        }

        void OnSchedulerError(object sender, FailedEventArgs e)
        {
            Action<FailedEventArgs> action = args =>
            {
                Message.Tips(args.Exception.Message, "温馨提示");
            };

            action.UIThreadInvoke(e);
        }

        void OnSchedulerStateChanged(object sender, StateChangedArgs e)
        {
        }

        void OnTaskStated(object sender, EventArgs e)
        {
            Action<ITask> action = task =>
            {
                ProgressEnabled = true;
            };

            action.UIThreadInvoke(sender as ITask);
        }

        void OnTaskCompleted(object sender, EventArgs e)
        {
            Action action = () =>
            {
                FeeHistories.Add(Context.Current.FeeHistories);
                ProgressEnabled = false;
            };

            action.UIThreadInvoke();
        }

        void OnFailed(object sender, FailedEventArgs e)
        {
            Action<FailedEventArgs> action = args =>
            {
                Message.Tips(args.Exception.Message, "温馨提示");
            };

            action.UIThreadInvoke(e);
        }

        void OnFlashed(object sender, EventArgs e)
        {
            Action<FeeHistoryTask> action = task =>
            {
                if (!task.NotSupportedHistory)
                {
                    FeeHistories.Add(task.History);
                }
            };

            action.UIThreadInvoke(sender as FeeHistoryTask);
        }

        public void ForceUpdateHistories()
        {
            ApplicationSettings.Settings.PrimelyFeeHistoryDate = DateTime.MinValue;
            scheduler.Schedule(GenerateFeeHistoriesTask());
        }

        Command moreFeeHistoriesCommand;
        public ICommand MoreFeeHistoriesCommand
        {
            get
            {
                if (moreFeeHistoriesCommand == null)
                {
                    moreFeeHistoriesCommand = new Command(param =>
                    {
                        DateTime occurred;
                        if (param != null && DateTime.TryParse(param.ToString(), out occurred))
                        {
                            Navigate(new Uri(string.Format("/Views/FeeHistoryPage.xaml?year={0}&month={1}", occurred.Year, occurred.Month), UriKind.Relative));
                        }
                    });
                }

                return moreFeeHistoriesCommand;
            }
        }

        FeeHistoryCollection feeHistories;
        public FeeHistoryCollection FeeHistories
        {
            get { return feeHistories; }
            set
            {
                if (value != feeHistories)
                {
                    feeHistories = value;
                    NotifyPropertyChanged("FeeHistories");
                }
            }
        }

        bool progressEnabled;
        public bool ProgressEnabled
        {
            get { return progressEnabled; }
            set
            {
                if (value != progressEnabled)
                {
                    progressEnabled = value;
                    NotifyPropertyChanged("ProgressEnabled");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
